package com.dao.impl;

import com.dao.SalerDao;
import com.entity.Saler;
import com.util.DBUtil;

import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;

public class SalerDaoImpl implements SalerDao {

    /**
     * @param saler
     * @return
     */
    @Override
    public Boolean checkDuplicatedName(Saler saler) {
        List<Map<String, Object>> result =  DBUtil.executeQuery("select account_name from saler where account_name = ?", new Object[]{saler.getAccountName()});
        if(result.isEmpty()){
            return true;
        }else{
            return false;
        }

    }

    /**
     * @param saler
     * @return
     */
    @Override
    public Long checkPass(Saler saler) {
        String sql = "select password,saler_id from saler where account_name = ?";
        List<Map<String, Object>> result = DBUtil.executeQuery(sql, new Object[]{saler.getAccountName()});
        if(result.isEmpty()){
            return 0L;
        }
        Boolean checkPass = saler.getPassWord().equals(result.get(0).get("password"));
        Long userId = (Long)result.get(0).get("saler_id");
        return userId;
    }

    /**
     * @param saler
     * @return
     */
    @Override
    public int createNewAccount(Saler saler) {
        int result = DBUtil.execute("insert into saler (account_name, password, saler_name, address, is_manager)values(?,?,?,?,?)", new Object[]{ saler.getAccountName(), saler.getPassWord(),saler.getSalerName(), saler.getAddress(),saler.getIsManager()});
        return result;
    }

    /**
     * @param id
     * @return
     */
    @Override
    public int deleteById(Long id) {
        int affectLines = DBUtil.execute("delete from saler where salerId = ?", new Object[]{id});
        return affectLines;
    }
    @Override
    public Saler findById(Long id) {

        Map<String,Object> map = DBUtil.executeQuery("select * from saler where saler_Id = ?", new Object[]{id}).get(0);
        return JSON.parseObject(JSON.toJSONString(map), Saler.class);
    }

    /**
     * @return
     */
    @Override
    public int updateAccount(Saler saler) {
        int affectLines = DBUtil.execute("update saler set salerName = ?, accountName = ?, passWord = ?, address = ? where salerId = ?", new Object[]{saler.getSalerName(), saler.getAccountName(), saler.getPassWord(), saler.getAddress(), saler.getSalerId()});
        return affectLines;
    }

}
